/*
 * Lenovo Group
 * Copyright (c) 2015-2016 All Rights Reserved.
 * 
 * Project Name:assign-tracer
 * Create Time: 2016年2月25日 上午9:21:45
 */
package com.lenovo.lmrp.server.assigntracer.domain.workflow;

import java.util.Date;

import org.activiti.engine.delegate.DelegateExecution;
import org.activiti.engine.delegate.ExecutionListener;
import org.activiti.engine.delegate.event.ActivitiEvent;
import org.activiti.engine.delegate.event.ActivitiEventListener;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.lenovo.lmrp.api.model.entity.TicketProcessPO.ProcessInstStatus;
import com.lenovo.sdc.framework.dao.ADaoFactory;
import com.lenovo.sdc.framework.dao.ICommonDAO;
import com.lenovo.sdc.framework.util.exception.ErrorCode;
import com.lenovo.sdc.framework.util.exception.TraceableException;

/**
 * 
 * @author wujin
 * @version v1.0
 */
public class ProcessEventListener implements ActivitiEventListener, ExecutionListener {

    private static final long serialVersionUID = 1L;

    private static final Logger logger = LoggerFactory.getLogger(ProcessEventListener.class);

    @Override
    public void notify(DelegateExecution execution) throws Exception {
        logger.debug("{} {} {}", execution.getCurrentActivityId(), execution.getEventName(),
            execution.getProcessInstanceId());
        try (ICommonDAO dao = ADaoFactory.getDefault().createDAO()){
            dao.beginTrans();
            if (execution.getEventName().equals("end")) {
                if (execution.getCurrentActivityId().equals("waitStartSignal")) {
                    dao.executeSQL("update lmrp_ticket_process set status = ? where instanceid = ?", 
                        new Object[]{ProcessInstStatus.RUNNING.ordinal(), execution.getProcessInstanceId()});
                }
                else if (execution.getCurrentActivityId().equals("endEvent")) {
                    dao.executeSQL("update lmrp_ticket_process set status = ?, endTime = ? where instanceid = ?", 
                        new Object[]{ProcessInstStatus.STOPED.ordinal(), new Date(), execution.getProcessInstanceId()});
                }
            }
            else if (execution.getEventName().equals("start")){
                dao.executeSQL("update lmrp_ticket_process set activityKey = ? where instanceid = ?", 
                    new Object[]{execution.getCurrentActivityId(), execution.getProcessInstanceId()});
            }
            
            dao.endTrans();
        }
        catch (Exception exp) {
            TraceableException.writeLog(ErrorCode.DB_UPDATE_FAILED, "lmrp_ticket_process", exp);
        }
    }

    @Override
    public void onEvent(ActivitiEvent event) {
        logger.debug("{} {} {}", event.getProcessInstanceId(), event.getType().toString(), event.getExecutionId());
    }

    @Override
    public boolean isFailOnException() {
        return false;
    }

}
